package com.fanshuai.spring.boot.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
public class MybatisPlusConfig {
    @Value("${druid.xa.enabled:false}")
    private boolean druidXAEnabled;

    private MybatisConfiguration configuration() {
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setCacheEnabled(true);
        configuration.setLazyLoadingEnabled(true);
        configuration.setMultipleResultSetsEnabled(true);

        configuration.setUseGeneratedKeys(true);
        configuration.setMapUnderscoreToCamelCase(true);

        return configuration;
    }

    @Bean(name = "sqlSessionFactoryPlus1")
    @Primary
    public SqlSessionFactory sqlSessionFactoryPlus1(DruidDataSource dataSource1) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource1);
        bean.setConfiguration(configuration());
        return bean.getObject();
    }

    @Bean(name = "sqlSessionFactoryPlus2")
    public SqlSessionFactory sqlSessionFactoryPlus2(@Qualifier("dataSource2") DruidDataSource dataSource2) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource2);
        bean.setConfiguration(configuration());
        return bean.getObject();
    }

    @Bean(name = "mapperScannerConfigurerPlus")
    public MapperScannerConfigurer mapperScannerConfigurerPlus(SqlSessionFactory sqlSessionFactoryPlus1) {
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setBasePackage("com.fanshuai.spring.boot.local.mybatisplus.mapper");
        configurer.setSqlSessionFactory(sqlSessionFactoryPlus1);

        return configurer;
    }

    @Bean(name = "mapperScannerConfigurerPlus2")
    public MapperScannerConfigurer mapperScannerConfigurerPlus2(@Qualifier("sqlSessionFactoryPlus2") SqlSessionFactory sqlSessionFactoryPlus2) {
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setBasePackage("com.fanshuai.spring.boot.local.mybatisplus.mapper2");
        configurer.setSqlSessionFactory(sqlSessionFactoryPlus2);

        return configurer;
    }

}
